<meta charset="UTF-8">
<div id="querydev">
    <div class="full">
        <h3 class="h3-title">{{$t("bgMgr.queryDev")}}</h3>
        <ul>
            <li>
                <i-input v-model.trim="queryParameter"></i-input>
            </li>
            <li>
                <i-button type="primary" @click="handlerClickQuery">{{$t("reportForm.query")}}</i-button>
            </li>
            <li style="float:right;width:auto;">
                <i-button @click="exportDevice">导出当前设备</i-button>
            </li>
        </ul>

        <div class="table-wraper">
            <i-table border 
                ref="table" 
                :columns="columns" 
                :data="tableData" 
                height="520" 
                :loading="loading"></i-table>
        </div>
        <div class="my-page" style="margin: 5px 0;">
            <Page :total="total" :page-size="10" :current="currentIndex"  @on-change="changePage"></Page>
        </div>

        <Modal v-model="modal" width="900" title="编辑设备">
            <div style="width:700px;margin:10px auto">
                <Row style="margin: 10px 0" v-if="userType == 0 || userType == 1">
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;选择账号 : &nbsp;</i-col>
                    <i-col span="8">
                        <div class="search-wrapper">
                            <i-input v-model.trim="createrToUser"  :icon="iconState" @on-change="sosoValueChange" @on-blur="blur" @on-focus="focus"></i-input>
                            <transition name="fade">
                                <ul class="search-item-wrapper" v-show="isShowMatchDev" style="cursor: pointer;">
                                    <li v-for="item in userlists" style="padding:5px 10px;" @click="selectedCmd(item)" :class="{'ivu-select-item-focus':item == createrToUser}">
                                        <Option :value="item" :key="item">
                                            <span style="cursor: pointer;">{{ item }}</span>
                                        </Option>
                                    </li>
                                </ul>
                            </transition>
                        </div>
                    </i-col>
                </Row>
                <Row style="margin: 10px 0">
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;终身免费 : &nbsp;</i-col>
                    <i-col span="8">  
                        <i-select v-model="isfree" style="width: 100%" :disabled="disabled">
                            <i-option value="1">是</i-option>
                            <i-option value="0">否</i-option>
                        </i-select>
                    </i-col>
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">SIM : &nbsp;</i-col>
                    <i-col span="8">
                        <i-input v-model.trim.number="simnum"></i-input>
                    </i-col>  
                </Row>
                <Row style="margin: 10px 0">
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("alarm.overdueTime")}} : &nbsp;</i-col>
                    <i-col span="8">
                        <date-picker type="date" v-model="overduetime" :disabled="disabled"></date-picker>
                    </i-col>
    
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("alarm.devName")}} : &nbsp;</i-col>
                    <i-col span="8">
                        <i-input v-model.trim="devicename"></i-input>
                    </i-col>
                    
                </Row>
    
                <Row style="margin: 10px 0">
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("user.devType")}} : &nbsp;</i-col>
                    <i-col span="8">  
                        <!-- devicetype -->
                        <i-select v-model="devicetype" :disabled="disabled">
                            <i-option v-for="item in deviceTypeList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                        </i-select>
                    </i-col>
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("alarm.devNum")}} : &nbsp;</i-col>
                    <i-col span="8">
                            <i-input v-model.trim="deviceid" disabled></i-input>
                    </i-col>
                    
                </Row>
    
                <Row style="margin: 10px 0"> 
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("user.grouping")}} : &nbsp;</i-col>
                    <i-col span="8">
                        <i-select v-model="groupid">
                            <i-option v-for="item in groupList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                        </i-select>
                    </i-col>
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;网络类型 : &nbsp;</i-col>
                    <i-col span="8">
                        <i-select v-model="teltype">
                            <i-option value="1">2G</i-option>
                            <i-option value="2">3G</i-option>
                            <i-option value="3">4G</i-option>
                        </i-select>
                    </i-col> 
                </Row>
    
                <Row style="margin: 10px 0">
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.reportCount")}}
                        : &nbsp;</i-col>
                    <i-col span="8">
                        <i-input v-model.trim="reportedpoint"></i-input>
                    </i-col>
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.allReportCount")}} : &nbsp;</i-col>
                    <i-col span="8">
                        <i-input v-model.trim="totalpoint"></i-input>
                    </i-col>
                </Row>
    
                <Row style="margin: 10px 0">
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.isUse")}} : &nbsp;</i-col>
                    <i-col span="8">
                        <i-select v-model="deviceenable">
                            <i-option value="0">{{$t("user.ban")}}</i-option>
                            <i-option value="1">{{$t("user.allow")}}</i-option>
                        </i-select>
                    </i-col>
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;监护账号 : &nbsp;</i-col>
                    <i-col span="8">
                        <i-input v-model.trim="monitor"></i-input>
                    </i-col>
                </Row>
               
    
                <Row style="margin: 10px 0">
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;下级编辑 : &nbsp;</i-col>
                    <i-col span="8">
                        <i-select v-model="allowedit" :disabled="isAlloweditDisabled">  
                            <i-option value="0">{{$t("user.ban")}}</i-option>
                            <i-option value="1">{{$t("user.allow")}}</i-option> 
                        </i-select>
                    </i-col>
                    <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.allowLogin")}} : &nbsp;</i-col>
                    <i-col span="8">
                        <i-select v-model="loginenable">
                            <i-option value="0">{{$t("user.ban")}}</i-option>
                            <i-option value="1">{{$t("user.allow")}}</i-option>     
                        </i-select>
                    </i-col>     
                </Row>    
                <Row style="margin: 10px 0">  
                        <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;转发地址 : &nbsp;</i-col>
                        <i-col span="20">
                            <i-input v-model.trim="forwardurl"></i-input>
                        </i-col>
                </Row>              
                <Row style="margin: 10px 0">
                    <i-col span="6" :offset="7">
                        <i-button style="width: 100%" @click="handleSubmit">{{$t("bgMgr.submit")}}</i-button>
                    </i-col>
                    <i-col span="6" :offset="1">
                        <i-button style="width: 100%" @click="resetInfo">{{$t("bgMgr.reset")}}</i-button>
                    </i-col>
                </Row>
            </div>
            <div slot="footer" style="height:20px;"></div>
        </Modal>
    </div>
    <script>
vueInstanse = new Vue({
            el:"#querydev",
            i18n: utils.getI18n(),
            data:{
                userType:Cookies.get('userType'),
                modal:false,
                queryParameter:"",
                loading:true,
                total:0,
                currentIndex:1,
                teltype:'1',
                columns: [
                    {
                        title: vRoot.$t("alarm.devName"),
                        key: 'devicename',
                    },
                    {
                        title: vRoot.$t("alarm.devNum"),
                        key: 'deviceid'
                    },
                    {
                        title: vRoot.$t("monitor.phoneNumber"),
                        key: 'simnum'
                    },
                    {
                        width:100,
                        title:  vRoot.$t("bgMgr.bindpwd"),
                        key: 'bindpwd',
                    },

                    {
                        title: vRoot.$t("bgMgr.addTime"),
                        key: 'createtimestr'
                    },
                    {
                        title: vRoot.$t("monitor.expireTime"),
                        key: 'overduetimestr'
                    },
                    {
                        title: vRoot.$t("monitor.customer"),  
                        key: 'companyname'
                    },
                    {
                        title: vRoot.$t("user.grouping"),
                        key: 'groupname'
                    },
                    {
                        title: vRoot.$t("bgMgr.action"),
                        key: 'action',
                        width: 240,
                        render: function(h, params) {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: function() {
                                            // vueInstanse.editDevice(params.row);
                                            vueInstanse.editDeviceIndex = params.index;
                                            editObject = params.row;
                                            vueInstanse.setDeviceData();
                                            vueInstanse.modal = true;
                                        }
                                    }
                                }, vRoot.$t("bgMgr.edit")),
                                 h('Poptip', {
                                    props: {
                                        confirm: true,
                                        title: vRoot.$t("message.confirmDel")  
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        'on-ok': function () {
                                            vueInstanse.handleDelete(params.row.deviceid);
                                        }
                                    }
                                },[
                                    h('Button', {
                                        props: {
                                            type: 'error',
                                            size: 'small',
                                            disabled: Cookies.get('userType') !== '0'

                                        }},vRoot.$t("bgMgr.delete")) 
                                 ]
                                ) ,
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: function() {
                                            vueInstanse.resetDevicePwd(params.index);
                                        }
                                    }
                                }, vRoot.$t("user.resetPwd")),
                                
                            ]);
                        }
                    }
                ],
                editDeviceIndex:null,
                queryTableData:[],
                tableData: [],
                recordsList:[],
                customersList:null,
                groupsList:[],
                
                iconState:"ios-arrow-down",
                deviceid:"",
                devicename:"",
                devicetype:"",
                simnum:"",
                overduetime:"",
                loginenable:"1",
                deviceenable:"0",
                groupList:[],
                deviceTypeList:[],
                reportedpoint:0,
                totalpoint:1500,
                groupid:'',
                companyid:'',
                forwardurl:"",
                allowedit:'0',
                createrToUser:"",
                userlists:[],
                isShowMatchDev:false,
                monitor:"",
                isfree:'1'
            },
            methods: {
                handlerClickQuery () {
                    var self = this;
                    var queryTableData = [];
                    var queryParameterLowerCase = this.queryParameter.toLowerCase();
                    if (!self.queryParameter){
                        return;
                    };

                    this.recordsList.forEach(function (record) {
                        var deviceid = record.deviceid;
                        var devicename = record.devicename;
                        var monitor = record.monitor;
                   
                        if (
                            devicename.indexOf(self.queryParameter) != -1 || 
                            deviceid.indexOf(self.queryParameter) != -1 ||
                            record.pinYin.indexOf(queryParameterLowerCase) != -1 ||
                            record.firstLetter.indexOf(queryParameterLowerCase) != -1 ||
                            (record.forwardurl && record.forwardurl.indexOf(queryParameterLowerCase) != -1 )||
                            (monitor && (monitor.indexOf(self.queryParameter) != -1 ))
                        ){      
                            queryTableData.push(record);
                        }
                    });

                    this.currentIndex = 1;
                    this.queryTableData = queryTableData;
                    this.tableData = this.queryTableData.slice(0,10);
                    this.total = this.queryTableData.length;

                },
                filterDataInfo:function(devList){
                    var me = this;
                    var data = [];
                    devList.forEach(function (dev) { 
                        dev.createtimestr = DateFormat.longToDateTimeStr(dev.createtime,0);
                        dev.overduetimestr = DateFormat.longToDateTimeStr(dev.overduetime,0);
                        dev.companyname = me.getCustimerName(dev.companyid);
                        dev.groupname = me.getGroupName(dev.groupid);
                        dev.pinYin = __pinyin.getPinyin(dev.devicename);
                        dev.firstLetter = __pinyin.getFirstLetter(dev.devicename);
                        data.push(dev);
                    });
                    return data;
                },
                resetDevicePwd:function(index){
                    var me = this;
                    var deviceid = this.tableData[index].deviceid;
                    var url = myUrls.resetDeviceLoginPwd();
                    utils.sendAjax(url,{deviceid:deviceid},function (resp) { 
                        if(resp.status === 0){
                            me.$Message.success(( isZh ? "密码重置为:" : "Password reset to :") + resp.newpass);
                        }else{
                            me.$Message.error( isZh ? "密码重置失败" : "Password Reset Failed");
                        }
                    });
                },
                getCustimerName:function (custimerId) { 
                    var custimerName = "";
                    this.customersList.forEach(function (item) { 
                        if(item.companyid == custimerId){
                            custimerName = item.companyname;
                        }
                    });
                    return custimerName;
                },
                getGroupName:function (groupId) { 
                    var groupName = "";
                    this.groupsList.forEach(function (item) { 
                        if(item.groupid == groupId){
                            groupName = item.groupname;
                        }
                    });
                    return groupName;
                },
                getDeviceList:function(){
                    var me = this;
                    var url = myUrls.queryDeviceListWithGroupInfo();
                    utils.sendAjax(url,{},function(resp){
                        me.loading = false;
                        if(resp.status == 0 && resp.devices != null){           
                            me.recordsList = me.filterDataInfo(resp.devices);
                            me.tableData = me.recordsList.slice(0,10);
                            me.total = me.recordsList.length;
                        }else{
                            me.$Message.error(resp.cause);
                        }
                    });
                },
                queryAllCompanyInfo:function(claaback){
                    var url = myUrls.queryCompanyByCreater();
                    utils.sendAjax(url,{},claaback)
                },
                doQueryAllCompanyInfo:function(resp){
                    var me = this;
                    if(resp.status===0 && resp.records != null){
                        me.customersList = resp.records;
                    }
                    me.queryAllgroupsInfo();
                },
                queryAllgroupsInfo:function(){
                    var url = myUrls.queryGroupByUser();
                    utils.sendAjax(url,{},this.doQueryAllgroupsInfo);
                },
                doQueryAllgroupsInfo:function(resp){
                    var me = this,groupList = [];
                    if(resp.status === 0 && resp.grouplist!==null){
                        me.groupsList = resp.grouplist; 
                        resp.grouplist.forEach(function (group) { 
                            groupList.push({label:group.groupname,value:group.groupid});
                        })
                        me.groupList = groupList; 
                    }
                    me.getDeviceList();  
                },
                handleDelete:function(deviceid){
                    var me = this;
                    var url = myUrls.deleteDevice();
                    var data = {deviceid:deviceid};
                    utils.sendAjax(url,data,function (resp) { 
                        if(resp.status == 0){
                            isNeedRefresh = true;
                            if(deviceid == globalDeviceId){
                                globalDeviceId = "";
                                vRoot.$store.commit('currentDeviceId', "");
                            }
                            me.$Message.success(me.$t("message.deleteSucc"));
                            me.tableData.forEach(function (itme,index) { 
                                if(itme.deviceid == deviceid){
                                    me.$delete(me.tableData,index);
                                }
                            });

                            me.recordsList.forEach(function (itme,index) { 
                                if(itme.deviceid == deviceid){
                                    me.$delete(me.recordsList,index);
                                }
                            });

                            me.total = me.recordsList.length;
                            me.tableData = me.recordsList.slice( me.currentIndex - 1 , 10);
                        }else{
                            me.$Message.error(me.$t("message.deleteFail"));
                        }
                        me.modal = false;
                       
                    });
                }
                ,
                exportDevice:function(){
                    if(this.tableData.length){
                        this.$refs.table.exportCsv({
                            filename: 'deviceids',
                            columns: this.columns.filter((col, index) => index < 3),
                            data: this.tableData,
                            quoted:true,
                        });
                    }
                },

                handleSubmit:function(){
                    var me = this;
                    var url = myUrls.editDevice();
                    if(this.overduetime == ""){
                        me.$Message.error(me.$t("message.plSelectTime"));
                        return;
                    }

                    var data = {
                        deviceid:this.deviceid,
                        devicetype:this.devicetype,
                        overduetime:new Date(this.overduetime).getTime(),
                        loginenable:Number(this.loginenable),
                        deviceenable:Number(this.deviceenable),
                        isfree:Number(this.isfree),
                        allowedit:Number(this.allowedit)
                    };      
                    
                    if(this.devicename){ data.devicename = this.devicename;};
                    if(this.teltype){ data.teltype = Number(this.teltype);};
                    

                    if(this.simnum !== ""){
                        data.simnum = this.simnum;
                    };
                    if(this.groupid !== "" && this.groupsList.length){
                        data.groupid = this.groupid;
                    }else{
                        data.groupid = 0;
                    };

                    if( this.reportedpoint == 0 || this.reportedpoint && !isNaN(this.reportedpoint)){
                        data.reportedpoint = Number(this.reportedpoint);
                    }

                    if(this.totalpoint && !isNaN(this.totalpoint)){
                        data.totalpoint = Number(this.totalpoint);
                    }

                    data.monitor = this.monitor;
                    
                    this.forwardurl && (data.forwardurl = this.forwardurl);

                    if(this.userType == 0 || this.userType == 1 ){
                        data.creater = this.createrToUser;
                    }else{
                        data.creater = userName;
                    }     

                    utils.sendAjax(url,data,function (resp) { 
                        if(resp.status == 0){
                            editObject.teltype = String(data.teltype);
                            var newData = Object.assign(editObject,data);
                                newData.overduetimestr = DateFormat.longToDateTimeStr(data.overduetime,0);
                            me.tableData[me.editDeviceIndex] = newData; 
                            utils.changeSingleItemData(me.recordsList,newData,'deviceid');
                            isNeedRefresh = true;                     
                            me.$Message.success(me.$t("message.changeSucc"));
                        }else if(resp.status = -1){
                            if( resp.cause!== null && resp.cause.indexOf("token")!=-1){
                                window.location.href = "index.html";
                            }else{
                                me.$Message.error(me.$t("message.changeFail"));
                            }
                        }
                    });
                },
                resetInfo:function(){
                    this.devicename = "";
                    this.devicetype = "";
                    this.simnum = "";
                    this.overduetime = "";
                    this.loginenable = "0";
                    this.deviceenable = "0";
                    this.groupsList = "";
                    this.groupid = "";
                    this.reportedpoint = 0;
                    this.totalpoint = 1500;
                    this.forwardurl = "";
                    this.monitor= "";
                },
                setDeviceData:function(){ 
                    var me = this;
                    me.deviceid = editObject.deviceid;
                    me.simnum = editObject.simnum;
                    me.overduetime = editObject.overduetimestr;
                    me.devicename  = editObject.devicename;
                    me.groupid = editObject.groupid;
                    me.devicetype = editObject.devicetype;
                    me.loginenable = editObject.loginenable + "";
                    me.deviceenable = "" +  editObject.deviceenable;
                    me.reportedpoint = editObject.reportedpoint ;
                    me.totalpoint = editObject.totalpoint ;
                    me.forwardurl = editObject.forwardurl;
                    me.createrToUser = editObject.creater;
                    me.monitor = editObject.monitor;
                    me.isfree = String(editObject.isfree);
                    me.teltype = String(editObject.teltype);
                    me.allowedit = String(editObject.allowedit);
                },
                getDeviceType:function () { 
                    var me = this;
                    vstore.state.deviceTypes .forEach(function (item) { 
                        var label = item.typename;
                        if(item.remark){
                            label += "("+item.remark+")";
                        }
                        me.deviceTypeList.push({value:item.devicetypeid,label:label});
                    })

                },
                selectedCmd:function(item){
                    var me = this;
                    setTimeout(function () {
                        me.isShowMatchDev = false;
                        me.createrToUser = item;
                    }, 100)
                },
                sosoValueChange:function(){
                    var me = this;
                    var value = this.createrToUser.toLowerCase();

                    if (this.timeoutIns != null) {
                        clearTimeout(this.timeoutIns);
                    }

                    if (!value.trim()) {
                        this.userlists = userlists;
                        return;
                    }

                    this.timeoutIns = setTimeout(function () {
                        me.filterMethod(value);
                    }, 100);
                },
                focus: function () {
                    this.isShowMatchDev = true;
                },
                blur: function () {
                    var me = this
                    setTimeout(function () {
                        me.isShowMatchDev = false;
                    }, 300)
                },
                filterMethod:function(value){
                    var list = [];
                    userlists.forEach(function (itme) { 
                        if(itme.toLowerCase().indexOf(value) != -1){
                            list.push(itme);
                        }
                    })
                    this.userlists = list;
                },
            },
            watch: {
                isShowMatchDev:function(){
                    if(!this.isShowMatchDev){
                        this.iconState = "ios-arrow-down";
                    }else{
                        this.iconState = "ios-arrow-up";
                    }
                },
            },
            computed:{
                disabled:function(){
                    return this.userType !== '0';
                },
                isAlloweditDisabled:function(){
                    return !(Number( this.userType ) <= 1); 
                }
            },
            mixins:[mixIn],
            mounted:function () {
                this.queryAllCompanyInfo(this.doQueryAllCompanyInfo);
                userlists.push(userName);
                this.userlists = userlists;
                this.userType = vstore.state.userType;
                this.getDeviceType();  
            }
        })
    </script>
</div>